package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 *  服务实现类
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 查询店铺类型列表
     * @return
     */
    @Override
    public Result queryTypeList() {
        //1、从redis中查询商铺类型列表缓存
        String key = RedisConstants.CACHE_TYPE_LIST;
        String shopTypeListJson = stringRedisTemplate.opsForValue().get(key);
        //2、判断是否存在
        if (StrUtil.isNotBlank(shopTypeListJson)){
            //3、如果存在，直接返回列表集合
            List<ShopType> shopTypesList = JSONUtil.toList(shopTypeListJson, ShopType.class);
            return Result.ok(shopTypesList);
        }

        //4、不存在，查询数据库
        List<ShopType> shopTypesList = query().orderByAsc("sort").list();

        //6、存在，将查询到的商铺类型列表缓存至redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shopTypesList));

        //7、返回商铺类型列表
        return Result.ok(shopTypesList);
    }
}
